<template>
  <div class="page-container">
    <div class="content-wrapper">
      <!-- 顶部操作栏 -->
      <div class="top-actions">
        <el-button 
          icon="el-icon-upload2" 
          size="medium"
          @click="goToUpload"
          class="upload-btn"
        >
          上传文件
        </el-button>
        <el-input 
          v-model="searchText"
          placeholder="请输入文件名称"
          prefix-icon="el-icon-search"
          clearable
          class="search-input"
          @input="handleSearch"
        />
      </div>

      <!-- 文件列表标题 -->
      <div class="list-header">
        <div class="title">我的PDF论文上传列表</div>
        <div class="filter-btn">
          <el-badge is-dot>
            <i class="el-icon-select"></i>
            <span>筛选</span>
          </el-badge>
        </div>
      </div>

      <!-- 文件列表表格 -->
      <div class="table-container">
        <el-table 
          :data="filteredPaperList" 
          stripe 
          class="file-table"
          highlight-current-row 
          show-overflow-tooltip
          header-row-class-name="custom-class"
          :header-cell-style="{
            background: '#f8f9fa',
            color: '#2c3e50',
            height: '40px',
          }"
          @row-click="handleRowClick"
          :row-class-name="getRowClassName"
        >
          <!-- 文件名称列 -->
          <el-table-column label="文件名称" min-width="120" max-width="150">
            <template v-slot="scope">
              <div class="file-name-cell">
                <img src="@/assets/icon/pdf-red.png" class="pdf-icon" alt="PDF"/>
                <span class="file-name">{{ scope.row.name }}</span>
              </div>
            </template>
          </el-table-column>

          <!-- 上传时间列 -->
          <el-table-column label="上传时间" width="150">
            <template v-slot="scope">
              <div class="time-cell">
                {{ formatTime(scope.row.uploadTime) }}
              </div>
            </template>
          </el-table-column>

          <!-- 状态列 -->
          <el-table-column label="状态" width="90">
            <template v-slot="scope">
              <el-tag
                :type="getStatusType(scope.row.status)"
                :disable-transitions="true"
                size="small"
                style="display: flex; justify-content: center; align-items: center"
              >
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>

          <!-- 操作列 -->
          <el-table-column label="操作" width="260" fixed="right">
            <template v-slot="scope">
              <div class="action-buttons">
                <!-- 智读按钮 -->
                <el-button 
                  type="primary" 
                  icon="el-icon-reading" 
                  size="mini"
                  @click.stop="goToNotes(scope.row)"
                  :disabled="scope.row.status !== 'success'"
                  title="智读"
                >
                  智读
                </el-button>
                
                <!-- 下载按钮 -->
                <el-button 
                  type="success" 
                  icon="el-icon-download" 
                  size="mini"
                  @click.stop="downloadFile(scope.row)"
                  title="下载"
                >
                  下载
                </el-button>
                
                <!-- 删除按钮 -->
                <el-button 
                  type="danger" 
                  icon="el-icon-delete" 
                  size="mini"
                  @click.stop="confirmDelete(scope.row)"
                  title="删除"
                >
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>

          <!-- 自定义空数据时展示的内容 -->
          <template #empty>
            <div class="empty-container">
              <el-empty :image="require('@/assets/svg/empty.svg')" description="嗷呜~ 暂无数据" :image-size="100"/>
            </div>
          </template>
        </el-table>
      </div>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handlePageSizeChange"
          @current-change="handlePageNumChange"
          :current-page="pageNum"
          :page-sizes="[5, 6, 7]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
          small
          :pager-count="5"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import dayjs from 'dayjs';
import { getCurrentUserId } from '@/utils/auth.js';

export default {
  name: 'PaperManagementPage',
  data() {
    return {
      myPaperList: [],
      filteredPaperList: [],
      searchText: '',
      uid: getCurrentUserId() || 1,
      pageNum: 1,  // 当前页码
      pageSize: 6, // 每页显示的个数，默认6条
      total: 0,
      loading: false,
    };
  },
  methods: {
    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return '未知时间';
      return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss');
    },

    // 获取状态文字
    getStatusText(status) {
      const statusMap = {
        'uploading': '上传中',
        'parsing': '解析中',
        'success': '解析成功',
        'error': '解析失败',
        'upload_error': '上传失败'
      };
      return statusMap[status] || status;
    },

    // 获取状态类型
    getStatusType(status) {
      const typeMap = {
        'uploading': 'info',
        'parsing': 'warning',
        'success': 'success',
        'error': 'danger',
        'upload_error': 'danger'
      };
      return typeMap[status] || '';
    },

    // 获取行样式类名
    getRowClassName({ row }) {
      if (row.status === 'success') {
        return 'success-row';
      }
      return '';
    },

    // 跳转到上传页面
    goToUpload() {
      this.$router.push('/upload');
    },

    // 跳转到智读页面
    goToNotes(file) {
      console.log("=== 跳转到智读页面 ===");
      console.log("文件对象:", file);
      console.log("文件ID:", file.id, "类型:", typeof file.id);
      
      if (file.status !== 'success') {
        this.$message.warning('文件解析未完成，无法进行智读');
        return;
      }
      
      // 确保ID是字符串类型
      const fileId = file.id.toString();
      console.log("转换后的文件ID:", fileId, "类型:", typeof fileId);
      
      this.$router.push({
        path: '/notes',
        query: { fileId: fileId }
      });
    },

    // 处理行点击
    handleRowClick(row) {
      // 点击行时跳转到智读页面
      this.goToNotes(row);
    },

    // 下载文件
    downloadFile(file) {
      try {
        // 创建下载链接
        const link = document.createElement('a');
        link.href = file.downloadUrl;
        link.download = file.name;
        link.target = '_blank';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        this.$message.success('开始下载文件');
      } catch (error) {
        console.error('下载失败:', error);
        this.$message.error('下载失败，请重试');
      }
    },

    // 确认删除
    confirmDelete(file) {
      this.$confirm(
        `确认删除文件 "${file.name}" 吗？此操作不可恢复。`,
        '删除确认',
        {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true
        }
      ).then(() => {
        this.deleteFile(file);
      }).catch(() => {
        // 用户取消删除
      });
    },

    // 删除文件
    async deleteFile(file) {
      try {
        this.loading = true;
        const response = await this.$request.delete(`/pdf/delete/${file.id}`);
        
        if (response.code === '200') {
          this.$message.success('文件删除成功');
          // 重新加载数据
          this.load();
        } else {
          this.$message.error(response.msg || '删除失败');
        }
      } catch (error) {
        console.error('删除文件失败:', error);
        this.$message.error('删除失败，请重试');
      } finally {
        this.loading = false;
      }
    },

    // 处理搜索
    handleSearch() {
      this.filterData();
    },

    // 过滤数据
    filterData() {
      if (!this.searchText.trim()) {
        this.filteredPaperList = this.myPaperList;
      } else {
        const searchLower = this.searchText.toLowerCase();
        this.filteredPaperList = this.myPaperList.filter(file => 
          file.name.toLowerCase().includes(searchLower)
        );
      }
    },

    // 加载数据
    async load(pageNum) {
      if (pageNum) {
        this.pageNum = pageNum;
      }
      
      try {
        this.loading = true;
        const response = await this.$request.get('/pdf/selectByPage', {
          params: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            uid: this.uid
          }
        });

        if (response.code === '200') {
          this.myPaperList = response.data?.records || [];
          this.total = response.data?.total || 0;
          
          // 确保每个文件都有status字段，如果没有则默认为success
          this.myPaperList.forEach(file => {
            if (!file.status) {
              file.status = 'success';
            }
          });
          
          this.filterData(); // 应用搜索过滤
          console.log('加载的文件列表:', this.myPaperList);
        } else {
          this.$message.error('加载文件列表失败：' + response.msg);
        }
      } catch (error) {
        console.error('加载文件列表失败:', error);
        this.$message.error('加载文件列表失败，请检查网络连接');
      } finally {
        this.loading = false;
      }
    },

    // 处理页码变化
    handlePageNumChange(pageNum) {
      this.pageNum = pageNum;
      this.load(pageNum);
    },

    // 处理每页条数变化
    handlePageSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.pageNum = 1; // 重置到第一页
      this.load(1);
    },
  },
  
  mounted() {
    this.load();
  }
};
</script>

<style scoped>
/* 页面容器 - 居中布局 */
.page-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  justify-content: center;
  align-items: flex-start;
  padding: 20px;
}

/* 内容包装器 - 居中显示 */
.content-wrapper {
  width: 100%;
  max-width: 1200px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  min-height: calc(100vh - 40px);
}

/* 顶部操作栏 */
.top-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 32px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.upload-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.upload-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
}

.search-input {
  width: 200px;
}

/* 文件列表标题 */
.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 14px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.title {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.filter-btn {
  background: #e9ecef;
  padding: 8px 20px;
  margin-right: 20px;
  border-radius: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
  min-width: 80px;
  justify-content: center;
}

.filter-btn:hover {
  background: #dee2e6;
  transform: translateY(-1px);
}

/* 表格容器 */
.table-container {
  flex: 1;
  padding: 0;
  overflow: hidden;
  min-width: 0;
}

.file-table {
  width: 100%;
  border-radius: 0;
  overflow: hidden;
  table-layout: fixed;
}

/* 文件名单元格 */
.file-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
  max-width: 100%;
  min-width: 0;
}

.pdf-icon {
  width: 20px;
  height: 20px;
  flex-shrink: 0;
}

.file-name {
  color: #2c3e50;
  font-size: 13px;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
  min-width: 0;
}

/* 时间单元格 */
.time-cell {
  color: #6c757d;
  font-size: 13px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 6px;
  align-items: center;
  flex-wrap: nowrap;
  justify-content: flex-start;
  width: 100%;
  padding: 0 8px;
}

/* 空状态容器 */
.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
  background: #f8f9fa;
  border-radius: 12px;
  margin: 20px 0;
}

/* 分页容器 */
.pagination-container {
  padding: 10px 32px;
  background: #f8f9fa;
  border-top: 1px solid #e9ecef;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 表格样式穿透 */
:deep(.custom-class) {
  font-size: 14px;
  font-weight: 600;
  height: 40px;
  background: #f8f9fa !important;
}

:deep(.el-table) {
  border: none;
  table-layout: fixed;
}

:deep(.el-table th) {
  background: #f8f9fa !important;
  color: #2c3e50 !important;
  font-weight: 600;
  border-bottom: 2px solid #dee2e6;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.el-table td) {
  padding: 16px 0;
  border-bottom: 1px solid #f1f3f4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.success-row) {
  background: #f0f9ff;
}

:deep(.success-row:hover) {
  background: #e0f2fe !important;
}

:deep(.el-table tbody tr:hover > td) {
  background: #f8f9fa !important;
}

/* 搜索框样式 */
:deep(.el-input__inner) {
  border: 2px solid #e9ecef;
  border-radius: 25px;
  padding: 12px 20px 12px 45px;
  background: white;
  transition: all 0.3s ease;
}

:deep(.el-input__inner:focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

:deep(.el-input__prefix) {
  left: 15px;
}

/* 按钮样式 */
:deep(.el-button--mini) {
  padding: 5px 10px;
  font-size: 12px;
  border-radius: 4px;
  transition: all 0.3s ease;
  min-width: auto;
  height: 30px;
  line-height: 1;
  white-space: nowrap;
}

:deep(.el-button--mini:hover) {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

:deep(.el-button--mini .el-icon) {
  margin-right: 3px;
}

/* 标签样式 */
:deep(.el-tag) {
  border-radius: 12px;
  font-size: 12px;
  padding: 4px 10px;
  font-weight: 500;
}

/* 分页样式 */
:deep(.el-pagination) {
  text-align: center;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  flex-wrap: wrap;
  height: 40px;
}

:deep(.el-pagination .el-pager) {
  display: flex;
  align-items: center;
  gap: 4px;
  flex-wrap: nowrap;
  height: 32px;
}

:deep(.el-pagination .el-pager li) {
  border-radius: 6px;
  margin: 0;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 32px;
  height: 32px;
  float: none;
}

:deep(.el-pagination .el-pager li.active) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: 600;
}

:deep(.el-pagination .el-pager li:hover) {
  background: #e9ecef;
  transform: translateY(-1px);
}

:deep(.el-pagination .btn-prev),
:deep(.el-pagination .btn-next) {
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 32px;
  height: 32px;
  border-radius: 6px;
  float: none;
}

:deep(.el-pagination .el-pagination__sizes) {
  display: flex;
  align-items: center;
  margin: 0 8px;
  height: 32px;
}

:deep(.el-pagination .el-pagination__total) {
  display: flex;
  align-items: center;
  margin-right: 8px;
  height: 32px;
}

:deep(.el-pagination .el-pagination__jump) {
  display: flex;
  align-items: center;
  margin-left: 8px;
  white-space: nowrap;
  height: 32px;
}

:deep(.el-pagination .el-pagination__jump .el-input) {
  width: 50px;
  margin: 0 4px;
  display: flex;
  align-items: center;
}

:deep(.el-pagination .el-pagination__jump .el-input__inner) {
  text-align: center;
  padding: 0 4px;
  height: 32px;
  line-height: 32px;
  vertical-align: middle;
}

:deep(.el-pagination .el-pagination__jump .el-pagination__editor) {
  display: flex;
  align-items: center;
  height: 32px;
}

:deep(.el-pagination .el-pagination__jump .el-pagination__editor .el-input) {
  margin: 0 4px;
  display: flex;
  align-items: center;
}

:deep(.el-pagination .el-pagination__jump .el-pagination__editor .el-input__inner) {
  text-align: center;
  padding: 0 4px;
  height: 32px;
  line-height: 32px;
  vertical-align: middle;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-container {
    padding: 10px;
  }
  
  .content-wrapper {
    border-radius: 12px;
  }
  
  .top-actions {
    padding: 16px 20px;
    flex-direction: column;
    gap: 16px;
  }
  
  .search-input {
    width: 100%;
  }
  
  .list-header {
    padding: 12px 20px;
  }
  
  .table-container {
    padding: 0;
  }
  
  .pagination-container {
    padding: 12px 20px;
  }
  
  :deep(.el-table) {
    font-size: 12px;
  }
  
  :deep(.el-button--mini) {
    padding: 4px 8px;
    font-size: 11px;
  }
  
  .file-name-cell {
    gap: 8px;
  }
  
  .pdf-icon {
    width: 20px;
    height: 20px;
  }
}
</style>